/**
 * file:    /controllers/weibo.js
 * author:  burning<iburning@live.cn>
 * date:    2014-08-03
 */

var validator = require('validator');
var weiboApi = require('weibo-api');
var config = require('../config');
var User = require('../proxy/user');
var Controller = require('./controller');
var controller = Controller.create();
var pageInfo = controller.pageInfo;

weiboApi.init(config.weibo_app);


controller.oauth = function (req, res) {
    weiboApi.authorize(res);
};


controller.callback = function (req, res) {
    weiboApi.accessToken(req.query.code, function (err, token) {
        if (err) {
            res.send(err);
            return;
        }
        if (token.error) {
            res.send(token);
            return;
        }
        console.log('callback', token);
        req.session.weibo_token = token;
        weiboApi.token = token.access_token;
        User.findOneByWeiboUid(token.uid, '_id username avatar weibo_info', function (err, user) {
            pageInfo.title = 'Oauth';
            if (user) {
                setSession(req, user);
                setCookie(res, user);
                res.render('sign/oauth-success', {
                    pageInfo: pageInfo,
                    user: user
                });
            } else {
                // 自动创建账号
                weiboApi.usersShow(token.uid, function (err, data) {
                    var newUser = {
                        // username: data.name,
                        gender: data.gender,
                        avatar: data.profile_image_url,
                        weibo_info: {
                            active: true,
                            uid: token.uid,
                            token: token.access_token,
                            name: data.name,
                            avatar: data.profile_image_url
                        }
                    };
                    User.add(newUser, function (err, user) {
                        res.render('sign/oauth-success', {
                            pageInfo: pageInfo,
                            user: user
                        });
                    });
                });
            }
        });
    });
};


module.exports = controller;


function md5(str) {
    var md5sum = crypto.createHash('md5');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}


function setSession (req, user) {
    req.session.user = {
        _id: user._id,
        username: user.username,
        avatar: user.avatar
    };
    req.session.weibo = {
        uid: user.weibo_info.uid,
        token: user.weibo_info.token
    };
}


function setCookie(res, user) {
    var expire = 1000 * 60 * 60 * 24 * 30;
    var userCookie = [];
    userCookie.push(user._id);
    userCookie.push(user.username);
    userCookie.push(user.password);
    userCookie.push(user.avatar);
    res.cookie('user', userCookie.join('|'), {
        path: '/',
        maxAge: expire
    });

    if (user.weibo_info) {
        var weiboCookie = [];
        weiboCookie.push(user.weibo_info.uid);
        weiboCookie.push(user.weibo_info.token);
        res.cookie('weibo', weiboCookie.join('|'), {
            path: '/',
            maxAge: expire
        });
    }
}
